package com.kai.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.kai.Listener.DemoDataListener;
import com.kai.Mapper.DemoDataMapper;
import com.kai.Pojo.DemoData;
import com.kai.dao.DemoDAO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class uploadExcelController {

    @Resource
    private DemoDataMapper mapper;


    @Resource
    private DemoDAO DemoDao;

    //上传
    @RequestMapping("/uploadExcel")
    public JSONObject uploadExcel(MultipartFile file) throws IOException {
        JSONObject jsonObject = new JSONObject();
        EasyExcel.read(file.getInputStream(), DemoData.class, new DemoDataListener(DemoDao)).sheet().doRead();
        jsonObject.put("msg","上传成功");
        return jsonObject;
    }

    //下载
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {


        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), DemoData.class).sheet("模板").doWrite(data());
    }

    //写入的数据
    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 20; i++) {
            DemoData data = new DemoData();
            data.setString("字" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

}
